
package com.kanjian.music.download;

import java.io.File;
import java.util.ArrayList;

import android.database.sqlite.SQLiteConstraintException;
import android.text.TextUtils;

import com.kanjian.music.database.DatabaseManager;
import com.kanjian.music.database.DownloadListDao;
import com.kanjian.music.database.MusicDao;
import com.kanjian.music.entity.DownloadList;
import com.kanjian.music.entity.Music;
import com.kanjian.music.util.SDCardUtil;

import de.greenrobot.dao.WhereCondition;

public class MusicDownloadTask implements Runnable {

    public static MusicDownloadTask CURRENT_TASK;

    public Music mMusic;

    private MusicDownloader mDownloader = new MusicDownloader();

    private DownloadListDao mDownLoadListDao = DatabaseManager.session.getDownloadListDao();

    private MusicDao mMusicDao = DatabaseManager.session.getMusicDao();

    private String mDownloadDir = SDCardUtil.getMusicDownLoadDir() + File.separator;

    // 是否用户主动下载
    private boolean mIsFromUser;

    private DownloadList mDBItem;

    private static ArrayList<MusicDownloadListener> mDownloadListenerList;

    public static void registerMusicDownloadListener(MusicDownloadListener listener) {
        if (mDownloadListenerList == null) {
            mDownloadListenerList = new ArrayList<MusicDownloadListener>();
        }
        mDownloadListenerList.add(listener);
    }

    public static void unregisterMusicDownloadListener(MusicDownloadListener listener) {
        if (mDownloadListenerList != null) {
            mDownloadListenerList.remove(listener);
        }
    }

    public MusicDownloadTask(Music music, int priority, boolean isFromUser) {
        this.mMusic = music;
        this.mPriority = priority;
        this.mIsFromUser = isFromUser;
        music.mDownloadType = (isFromUser ? 0 : 1);
        mDBItem = new DownloadList();
        mDBItem.setMusicId(mMusic.getMusicId());
        mDBItem.setDownloadType(mIsFromUser ? 0 : 1);
        mDBItem.setDownloadStatus(-1);
        mDBItem.setDisplayOrder(System.currentTimeMillis());
        try {
            mDownLoadListDao.insert(mDBItem);
        } catch (SQLiteConstraintException e) {
            return;
        }
        mMusicDao.insertOrReplace(music);
    }

    public int mPriority;

    @Override
    public void run() {

        CURRENT_TASK = this;

        final String filePath = getDownloadFilePath();

        mDBItem.setLocalPath(filePath);
        // 设数据库状态为正在下载
        mDBItem.setDownloadStatus(1);
        mDBItem.setMusicId(mMusic.getMusicId());
        mDBItem.setDownloadType(mIsFromUser ? 0 : 1);
        mDownLoadListDao.insertOrReplace(mDBItem);

        mMusic.mLocalPath = filePath;

        mDownloader.downloadToFile(filePath, mMusic, new MusicDownloadListener() {

            @Override
            public void onStartDownload(Music music) {
                notifyOnStart(music);
            }

            @Override
            public void onProgress(Music music, int progress) {
                System.out.println(CURRENT_TASK);
                notifyOnProgress(music, progress);
            }

            @Override
            public void finishDownload(Music music, int downloadStatus) {
                if (downloadStatus == MusicDownloader.DOWNLOAD_STATUS_SUCCESS) {
                    mDBItem.setDownloadStatus(0);
                } else if (downloadStatus == MusicDownloader.DOWNLOAD_STATUS_USER_PAUSE) {
                    mDBItem.setDownloadStatus(-1);
                }
                mDBItem.setMusicId(mMusic.getMusicId());
                mDBItem.setDownloadType(mIsFromUser ? 0 : 1);
                mDBItem.setLocalPath(filePath);
                mDownLoadListDao.insertOrReplace(mDBItem);
                notifyOnFinish(music, downloadStatus);
            }
        });
    }

    private synchronized void notifyOnStart(Music music) {
        if (mDownloadListenerList != null) {
            for (MusicDownloadListener listener : mDownloadListenerList) {
                listener.onStartDownload(music);
            }
        }
    }

    private synchronized void notifyOnProgress(Music music, int progress) {
        if (mDownloadListenerList != null) {
            for (MusicDownloadListener listener : mDownloadListenerList) {
                listener.onProgress(music, progress);
            }
        }
    }

    private synchronized void notifyOnFinish(Music music, int downloadStatus) {
        if (mDownloadListenerList != null) {
            for (MusicDownloadListener listener : mDownloadListenerList) {
                listener.finishDownload(music, downloadStatus);
            }
        }
    }

    private String getDownloadFilePath() {

        DownloadList item = mDownLoadListDao.queryBuilder()
                .where(new WhereCondition.StringCondition(" music_id = " + mMusic.getMusicId()))
                .unique();
        if (item != null && !TextUtils.isEmpty(item.getLocalPath())) {
            return item.getLocalPath();
        }

        String filePath = mDownloadDir + System.currentTimeMillis() + ".mp3";
        if (new File(filePath).exists()) {
            filePath = getDownloadFilePath();
        }

        return filePath;
    }

    public void pause() {
        // 暂停时 把当前任务设为null
        if (CURRENT_TASK != null && CURRENT_TASK.mMusic.getMusicId() == mMusic.getMusicId()) {
            CURRENT_TASK = null;
        }
        if (mDownloader != null) {
            mDownloader.pause();
        }
    }

    public boolean isPaused() {
        return mDownloader.mIsPause;
    }

}
